import request from '../../uitls/request'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        articleList:[],//文章列表
        pageIndex:0,//文章列表分页
    },

    // 获取文章列表数据
    async getArticleListData(index){
        let {pageIndex} = this.data;
        let articleListData = await request('/user_article/list/'+index+'/json');
        this.setData({
            articleList:articleListData.data.datas,
        });
        wx.hideLoading();
    },

    // 跳转至详情页面
    toDetail(event){
        let deskUrl = event.currentTarget.dataset.url;
        wx.navigateTo({
          url: '/pages/webpage/webpage?url='+deskUrl,
        })
    },

     //列表下拉刷新回调
     async handlePullDownRefresh(){

        let {articleList} = this.data;

        let articleListData =  await request('/user_article/list/0/json');
        let newList = articleListData.data.datas.reverse();

        newList.forEach(element => {
            let articleItem = articleList.find(item => item.id === element.id);
            if(articleItem == null)
            {
                console.log(element);
                articleList.unshift(element);
            }
        });       

        this.setData({
            articleList
        });

        wx.stopPullDownRefresh();
    },

    //列表上划数据刷新回调
    async handleReachBottom(){
        let {pageIndex} = this.data;
        let {articleList} = this.data;

        let articleListData = await request('/user_article/list/'+ (++pageIndex)+'/json')
        let newList = articleListData.data.datas;

        newList.forEach(element => {
            let articleItem = articleList.find(item => item.id === element.id);
            if(articleItem == null)
            {
                articleList.push(element);
            }
        });       

        wx.hideLoading();

        this.setData({
            articleList,
            pageIndex
        });

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.showLoading({
            title: '正在加载',
          })
        this.getArticleListData(this.data.pageIndex);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

        this.handlePullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        wx.showLoading({
            title: '正在加载',
          });
          this.handleReachBottom();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})